<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="time">
  </div>

  <script>
    let el = document.querySelector('#time')

    const eventSource = new EventSource('http://localhost:3001/sse-eventsource')

    //  这样的写法也可以
    // eventSource.onopen = () => {}
    eventSource.addEventListener('open', () => {
      console.log('请求来了');
    })

    // eventSource.onmessage = () => {}
    eventSource.addEventListener('message', (event) => {
      console.log(event);
    })

    // eventSource.onerror
    eventSource.addEventListener('error', (error) => {
      console.log('发生了错误');
      console.log(error);
    })

    // 注意： 这里的event事件名 my-event是服务端定义的，切需要对应，下面的回调才能调用
    // 然后，服务端在指定的时候，一定不要加 单双引号，就裸字符串 event:my-event 就可以
    eventSource.addEventListener('my-event', (event) => {
      console.log(event);

      // 解析
      let data = event.data

      data = JSON.parse(data)

      console.log(data);

      el.innerHTML = event.data
    })
  </script>
</body>

</html>